# -*- coding: utf-8 -*-
# @Time    : 2024/5/11 14:35
# @Author  : Alvin
# @File    : minio_service.py
import requests
import io
from datetime import timedelta
from minio import Minio
from hashlib import sha256
import os
GLOBAL_HOST = os.getenv('GLOBAL_HOST', 'localhost')

expires_in = 7 * 24 * 3500
# 计算过期时间
expires_at = timedelta(seconds=expires_in)
# 初始化 MinIO 客户端
minio_client = Minio(
    f"{GLOBAL_HOST}:9090",
    access_key="minioadmin",
    secret_key="minioadmin",
    secure=False
)
img_format = '.webp'
# 检查 MinIO 桶是否存在，如果不存在则创建
bucket_name = "images"
if not minio_client.bucket_exists(bucket_name):
    minio_client.make_bucket(bucket_name)

def get_image_binary(url):
    response = requests.get(url)
    return response.content
# 下载图片到 MinIO 桶中
def download_image(image_binary, file_name):

    # 创建一个 BytesIO 对象来获取二进制数据的长度
    data_stream = io.BytesIO(image_binary)
    # 使用 put_object 方法将数据写入到 MinIO 桶中
    minio_client.put_object(bucket_name, file_name, data_stream, len(image_binary))
    # 关闭 BytesIO 对象
    data_stream.close()

def object_exists(minio_client, bucket_name, object_name):
    try:
        # 尝试获取对象的元数据信息
        minio_client.stat_object(bucket_name, object_name)
        # 如果没有引发异常，则对象存在
        return True
    except Exception as e:
        # 如果引发 NoSuchKey 异常，则对象不存在
        return False

# 获取图片预览链接的接口
# @minio_bp.route("/get_image_preview", methods=["GET"])
def get_image_preview_url(image_url):
    # 获取前端传递的图片 URL
    # image_url = request.args.get("image_url")

    # 计算图片 URL 的哈希值作为键值
    # image_hash = sha256(image_url.encode()).hexdigest()

    image_binary = get_image_binary(image_url)
    image_hash = sha256(image_binary).hexdigest()
    # 检查 MinIO 桶中是否存在该图片

    if object_exists(minio_client, bucket_name,  image_hash + img_format ):
        # 如果图片存在，返回图片的预览链接
        # image_preview_url = f"https://127.0.0.1:9000/{bucket_name}/{image_hash}.jpg"
        image_preview_url = minio_client.get_presigned_url(method='GET',bucket_name=bucket_name, object_name=image_hash + img_format, expires=expires_at,response_headers={"ResponseContentDisposition": "inline","Content-Type": "image/webp" })
        # return jsonify({"image_preview_url": image_preview_url})
        return image_preview_url
    else:
        # 如果图片不存在，先下载图片到 MinIO 桶中，再返回图片的预览链接
        download_image(image_binary, image_hash + img_format)
        image_preview_url = minio_client.get_presigned_url(method='GET',bucket_name=bucket_name, object_name=image_hash + img_format, expires=expires_at,response_headers={"ResponseContentDisposition": "inline","Content-Type": "image/webp" })
        return image_preview_url